layui.use(['layer','upload','laydate','layedit','treeSelect','table','form','laytpl','element'], function(){
    var $ = layui.$
        ,layer = layui.layer
        ,admin = layui.admin
        ,table = layui.table
        ,element = layui.element
        ,form = layui.form
        ,laytpl = layui.laytpl;
    var upload = layui.upload;
    var layedit = layui.layedit;
    var laydate = layui.laydate;

    //获取路径参数
    var request = GetRequest();
    $("#id").val(request.id);

    $.get("/process/qrcode/" + request.id,function (data) {
        if (data.tableDefaultValue != null && data.tableDefaultValue != '') {
            var defaultValueObj = JSON.parse(data.tableDefaultValue);

            $.get('/table/rows/list/' + request.tableName,function (data) {
                /*var obj = {};
                //表单数据
                $.ajax({
                    url: '/tracetable/selectone?id=' + request.id + "&tableName=" + request.tableName,
                    type: 'get',
                    async: false,
                    success: function (data) {
                        obj = data.data[0];
                    }
                });
                console.log(obj);*/
                console.log(defaultValueObj);
                $("#form-list").append('<div id="submit-btn" style="margin: 20px 0;" class="layui-form-item"><div class="layui-input-block"><button class="layui-btn" lay-submit lay-filter="add">提交修改</button></div></div>');

                //渲染提交的表单元素
                $.each(data.data,function (i,ele) {
                    for (var key in defaultValueObj) {
                        if (ele.formType == "input" && key == 'formData[' + i + ']') {
                            var innerHtml = '<div class="layui-form-item layui-row layui-col-xs12"> ' +
                                '        <div class="layui-col-lg6"> ' +
                                '            <label class="layui-form-label">'+ ele.nameZh + '</label> ' +
                                '            <div class="layui-input-block"> ' +
                                '                <input type="text" id="'+ ele.name +'" lay-verify="required" name="formData[]" placeholder="" autocomplete="off" class="layui-input" value="'+ defaultValueObj[key] +'"> ' +
                                '            </div> ' +
                                '        </div> ' +
                                '    </div>';
                            $("#submit-btn").before(innerHtml);
                        } else if (ele.formType == "textarea" && key == 'formData[' + i + ']') {
                            var innerHtml = '<div class="layui-form-item"> ' +
                                '    <div class="layui-col-lg6"> ' +
                                '      <label class="layui-form-label">'+ ele.nameZh + '</label> ' +
                                '      <div class="layui-input-block"> ' +
                                '        <textarea id="'+ ele.name +'"  name="formData[]" placeholder="请输入内容" class="layui-textarea">'+ defaultValueObj[key] +'</textarea> ' +
                                '      </div> ' +
                                '    </div> ' +
                                '  </div>';
                            $("#submit-btn").before(innerHtml);
                        } else if (ele.formType == "date" && key == 'formData[' + i + ']') {
                            var innerHtml = '<div class="layui-form-item layui-row layui-col-xs12"> ' +
                                '    <label class="layui-form-label">'+ ele.nameZh +'</label> ' +
                                '    <div class="layui-input-inline"> ' +
                                '      <input type="text" name="formData[]" id="time-'+ ele.name +'"  placeholder="" autocomplete="off" class="layui-input" value=""> ' +
                                '    </div> ' +
                                '  </div>';
                            $("#submit-btn").before(innerHtml);
                            //时间组件
                            laydate.render({
                                elem: '#time-' + ele.name
                                ,value: defaultValueObj[key] //必须遵循format参数设定的格式
                            });
                        } else if (ele.formType == "img" && key == 'formData[' + i + ']') {
                            window.rowsId = ele.id;
                            var innerHtml = '<div class="layui-form-item"> ' +
                                '    <div class="layui-col-lg6"> ' +
                                '      <label class="layui-form-label">'+ ele.nameZh +'</label> ' +
                                '      <input type="hidden" name="formData[]" id="'+ ele.name +'" value="'+ defaultValueObj[key] +'"> ' +
                                '      <div class="layui-input-block layui-upload"> ' +
                                '        <button type="button" class="layui-btn" id="uploadImg-'+ ele.id +'">图片上传</button> ' +
                                '        <blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 10px;"> ' +
                                '          预览图： ' +
                                '          <div class="layui-upload-list" id="showImg"><img width="30%" src="'+ defaultValueObj[key] +'" alt=""></div> ' +
                                '        </blockquote> ' +
                                '      </div> ' +
                                '    </div> ' +
                                '  </div>';
                            $("#submit-btn").before(innerHtml);
                            var $input = $("#" + ele.name);
                            //图片上传
                            upload.render({
                                elem: '#uploadImg-' + ele.id
                                ,url: '/upload/pic'
                                // ,multiple: true
                                ,field:"uploadFile"
                                ,before: function(obj){
                                }
                                ,done: function(res){
                                    //上传完毕
                                    var url = res.url;
                                    $('#showImg').html('');
                                    $('#showImg').append('<img style="padding: 10px" width="30%" src="'+ url +'" class="layui-upload-img">');
                                    $input.val(url);
                                }
                            });
                        } else if (ele.formType == "layedit" && key == 'formData[' + i + ']') {
                            var innerHtml = '<div class="layui-form-item magb0" id="layedit_content"> ' +
                                '    <label class="layui-form-label">'+ ele.nameZh +'</label> ' +
                                '    <div class="layui-input-block"> ' +
                                '      <textarea class="layui-textarea layui-hide" name="formData[]" lay-verify="content" id="layedit_content_'+ ele.id +'">'+ defaultValueObj[key] +'</textarea> ' +
                                '    </div> ' +
                                '  </div>';
                            $("#submit-btn").before(innerHtml);
                            //创建一个编辑器
                            window.editIndex = layedit.build('layedit_content_' + ele.id,{
                                height : 535,
                                uploadImage : {
                                    url : "/layedit/upload/pic"
                                }
                            });
                            layedit.setContent(editIndex,defaultValueObj[key]);
                            //用于同步编辑器内容到textarea
                            layedit.sync(editIndex);
                        }
                    }
                });

                form.render();
            });
        } else {
            $.get('/table/rows/list/' + request.tableName,function (data) {
                //渲染提交的表单元素
                $.each(data.data,function (i,ele) {
                    if (ele.formType == "input") {
                        var innerHtml = '<div class="layui-form-item layui-row layui-col-xs12"> ' +
                            '        <div class="layui-col-lg6"> ' +
                            '            <label class="layui-form-label">'+ ele.nameZh + '</label> ' +
                            '            <div class="layui-input-block"> ' +
                            '                <input type="text" lay-verify="required" name="formData[]" placeholder="" autocomplete="off" class="layui-input" value=""> ' +
                            '            </div> ' +
                            '        </div> ' +
                            '    </div>';
                        $("#form-list").append(innerHtml);
                    } else if (ele.formType == "textarea") {
                        var innerHtml = '<div class="layui-form-item"> ' +
                            '    <div class="layui-col-lg6"> ' +
                            '      <label class="layui-form-label">'+ ele.nameZh + '</label> ' +
                            '      <div class="layui-input-block"> ' +
                            '        <textarea name="formData[]" placeholder="请输入内容" class="layui-textarea"></textarea> ' +
                            '      </div> ' +
                            '    </div> ' +
                            '  </div>';
                        $("#form-list").append(innerHtml);
                    } else if (ele.formType == "date") {
                        var innerHtml = '<div class="layui-form-item layui-row layui-col-xs12"> ' +
                            '    <label class="layui-form-label">'+ ele.nameZh +'</label> ' +
                            '    <div class="layui-input-inline"> ' +
                            '      <input type="text" name="formData[]" id="time-'+ ele.id +'" placeholder="" autocomplete="off" class="layui-input" value=""> ' +
                            '    </div> ' +
                            '  </div>';
                        $("#form-list").append(innerHtml);
                        //时间组件
                        laydate.render({
                            elem: '#time-' + ele.id
                        });
                    } else if (ele.formType == "img") {
                        window.rowsId = ele.id;
                        var innerHtml = '<div class="layui-form-item"> ' +
                            '    <div class="layui-col-lg6"> ' +
                            '      <label class="layui-form-label">'+ ele.nameZh +'</label> ' +
                            '      <input type="hidden" name="formData[]" id="'+ ele.name +'"> ' +
                            '      <div class="layui-input-block layui-upload"> ' +
                            '        <button type="button" class="layui-btn" id="uploadImg-'+ ele.id +'">图片上传</button> ' +
                            '        <blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 10px;"> ' +
                            '          预览图： ' +
                            '          <div class="layui-upload-list" id="showImg"></div> ' +
                            '        </blockquote> ' +
                            '      </div> ' +
                            '    </div> ' +
                            '  </div>';
                        $("#form-list").append(innerHtml);
                        var $input = $("#" + ele.name);
                        //图片上传
                        upload.render({
                            elem: '#uploadImg-' + ele.id
                            ,url: '/upload/pic'
                            // ,multiple: true
                            ,field:"uploadFile"
                            ,before: function(obj){
                            }
                            ,done: function(res){
                                //上传完毕
                                var url = res.url;
                                $('#showImg').html('');
                                $input.val('');
                                $('#showImg').append('<img style="padding: 10px" width="30%" src="'+ url +'" class="layui-upload-img">');
                                $input.val(url);
                            }
                        });
                    } else if (ele.formType == "layedit") {
                        var innerHtml = '<div class="layui-form-item magb0"> ' +
                            '    <label class="layui-form-label">'+ ele.nameZh +'</label> ' +
                            '    <div class="layui-input-block"> ' +
                            '      <textarea class="layui-textarea layui-hide" name="formData[]" lay-verify="content" id="layedit_content_'+ ele.id +'"></textarea> ' +
                            '    </div> ' +
                            '  </div>';
                        $("#form-list").append(innerHtml);
                        //创建一个编辑器
                        window.editIndex = layedit.build('layedit_content_' + ele.id,{
                            height : 535,
                            uploadImage : {
                                url : "/layedit/upload/pic"
                            }
                        });
                        form.verify({
                            content: function(value) {
                                return layedit.sync(editIndex);
                            }
                        });
                        //用于同步编辑器内容到textarea
                        layedit.sync(editIndex);
                    }

                });
                $("#form-list").append('<div style="margin: 20px 0;" class="layui-form-item"><div class="layui-input-block"><button class="layui-btn" lay-submit lay-filter="add">提交修改</button></div></div>');
                form.render();
            });
        }
    });


    //修改默认值
    form.on('submit(add)', function(data){
        //封装默认信息，遍历对象data.field
        var dataObj = {};
        dataObj.id = data.field.id;
        var tableDefaultValue = {};
        for (var key in data.field) {
            if (key != 'id') {
                tableDefaultValue[key] = data.field[key];
            }
        }
        dataObj.tableDefaultValue = JSON.stringify(tableDefaultValue);

        var index = top.layer.msg('数据提交中，请稍候',{icon: 16,time:false,shade:0.8});
        //初始化数据
        $.ajax({
            url: '/process/qrcode/edit',
            data: dataObj,
            type: 'POST',
            async: false,
            success: function (data) {
                if(data.code == 200) {
                    top.layer.close(index);
                    top.layer.msg("修改成功！");
                    layer.closeAll("iframe");
                    //刷新父页面
                    parent.location.reload();
                } else {
                    top.layer.close(index);
                    top.layer.msg("修改失败！");
                }
            },
            error:function () {
                top.layer.close(index);
                top.layer.msg("修改失败！");
            }
        });
        return false;
    });

    /**
     * 获取路径中的参数
     * @returns {Object}
     */
    function GetRequest() {
        var url = location.search;         //获取url中"?"符后的字串
        var theRequest = new Object();
        if (url.indexOf("?") != -1) {
            var str = url.substr(1);
            var strs = str.split("&");
            for (var i = 0; i < strs.length; i++) {
                theRequest[strs[i].split("=")[0]] = decodeURIComponent(strs[i].split("=")[1]);
            }
        }
        return theRequest;
    }

});

